package com.costaccounting.base.service.impl;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import com.costaccounting.base.domain.ZsCategoryPersonConfig;
import com.costaccounting.base.domain.ZsItem;
import com.costaccounting.base.service.IZsCategoryPersonConfigService;
import com.costaccounting.base.service.IZsItemService;
import com.costaccounting.common.constant.UserConstants;
import com.costaccounting.common.core.domain.AjaxResult;
import com.costaccounting.common.core.domain.entity.SysDept;
import com.costaccounting.common.exception.ServiceException;
import com.costaccounting.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.costaccounting.base.mapper.ZsCategoryMapper;
import com.costaccounting.base.domain.ZsCategory;
import com.costaccounting.base.service.IZsCategoryService;

/**
 * 类目管理Service业务层处理
 *
 * @author H
 * @date 2021-11-06
 */
@Service
public class ZsCategoryServiceImpl implements IZsCategoryService {
    @Autowired
    private ZsCategoryMapper zsCategoryMapper;
    @Autowired
    private IZsCategoryPersonConfigService categoryPersonConfigService;
    @Autowired
    private IZsItemService itemService;
    @Autowired
    private IZsCategoryService categoryService;

    /**
     * 查询类目管理
     *
     * @param id 类目管理主键
     * @return 类目管理
     */
    @Override
    public ZsCategory selectZsCategoryById(Long id) {
        ZsCategory category = zsCategoryMapper.selectZsCategoryById(id);
        if (0 != category.getPid()) {
            ZsCategory category1 = zsCategoryMapper.selectZsCategoryById(category.getPid());
            category.setPname(category1.getName());
        }
        return category;
    }

    /**
     * 查询类目管理列表
     *
     * @param zsCategory 类目管理
     * @return 类目管理
     */
    @Override
    public List<ZsCategory> selectZsCategoryList(ZsCategory zsCategory) {
        return zsCategoryMapper.selectZsCategoryList(zsCategory);
    }

    /**
     * 新增类目管理
     *
     * @param zsCategory 类目管理
     * @return 结果
     */
    @Override
    public int insertZsCategory(ZsCategory zsCategory) {
        //检查重名
//        ZsCategory category = new ZsCategory();
//        category.setName(zsCategory.getName());
//        List<ZsCategory> zsCategories = zsCategoryMapper.selectZsCategoryList(category);
//        if (0 < zsCategories.size()) {
//            throw new ServiceException("已有名为【" + zsCategory.getName() + "】的类目，不可新增");
//        }
        zsCategory.setCreateTime(DateUtils.getNowDate());
        if (0 != zsCategory.getPid()) {
            ZsCategory info = zsCategoryMapper.selectZsCategoryById(zsCategory.getPid());
            // 如果父节点不为正常状态,则不允许新增子节点
            if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
                throw new ServiceException("类目【" + info.getName() + "】停用，不可新增");
            }
            zsCategoryMapper.insertZsCategory(zsCategory);
            zsCategory.setAncestors(info.getAncestors() + "," + zsCategory.getId());
            return zsCategoryMapper.updateZsCategory(zsCategory);
        }
        zsCategoryMapper.insertZsCategory(zsCategory);
        zsCategory.setAncestors(zsCategory.getId().toString());
        return zsCategoryMapper.updateZsCategory(zsCategory);
    }

    /**
     * 修改类目管理
     *
     * @param zsCategory 类目管理
     * @return 结果
     */
    @Override
    public int updateZsCategory(ZsCategory zsCategory) {
        //检查重名
//        ZsCategory category = new ZsCategory();
//        category.setName(zsCategory.getName());
//        List<ZsCategory> zsCategories = zsCategoryMapper.selectZsCategoryList(category);
//        if (0 < zsCategories.size()) {
//            if (!zsCategories.get(0).getId().equals(zsCategory.getId())) {
//                throw new ServiceException("已有名为【" + zsCategory.getName() + "】的类目，不可新增");
//            }
//        }

        zsCategory.setUpdateTime(DateUtils.getNowDate());

        if (0 != zsCategory.getPid()) {
            ZsCategory info = zsCategoryMapper.selectZsCategoryById(zsCategory.getPid());
            // 如果父节点不为正常状态,则不允许新增子节点
            if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
                throw new ServiceException("类目【" + info.getName() + "】停用，不允许新增");
            }
            zsCategory.setAncestors(info.getAncestors() + "," + zsCategory.getId());
            return zsCategoryMapper.updateZsCategory(zsCategory);
        }
        zsCategory.setAncestors(zsCategory.getId().toString());
        return zsCategoryMapper.updateZsCategory(zsCategory);
    }

    /**
     * 批量删除类目管理
     *
     * @param ids 需要删除的类目管理主键
     * @return 结果
     */
    @Override
    public int deleteZsCategoryByIds(Long[] ids) {
        return zsCategoryMapper.deleteZsCategoryByIds(ids);
    }

    /**
     * 删除类目管理信息
     *
     * @param id 类目管理主键
     * @return 结果
     */
    @Override
    public int deleteZsCategoryById(Long id) {
        return zsCategoryMapper.deleteZsCategoryById(id);
    }

    @Override
    public AjaxResult deleteByIds(Long[] ids) {
        for (Long id : ids) {
            ZsCategory category = new ZsCategory();
            category.setPid(id);
            List<ZsCategory> zsCategories = zsCategoryMapper.selectZsCategoryList(category);
            if (0 < zsCategories.size()) {
                return AjaxResult.error("此类目下存在分类，不可删除");
            }
        }
        return AjaxResult.success(zsCategoryMapper.deleteZsCategoryByIds(ids));
    }

    //获取未与操作员分配的类目
    @Override
    public List<ZsCategory> getNoList(ZsCategoryPersonConfig categoryPersonConfig) {
        /**
         *  0，获取项目下所有分类
         *  1，获取所有最下级类目/获取已选中
         *  2，将已选中类目剔除
         *  3，获取剩余类目所有上级
         */

        List<Long> allCateIds = new ArrayList<>();
        //获取项目下所有分类
        ZsItem zsItem = itemService.selectZsItemById(categoryPersonConfig.getItemId());
        if (null!=zsItem.getCategoryIds()&&!"".equals(zsItem.getCategoryIds())) {
            String[] allIds = zsItem.getCategoryIds().split(",");
            for (int i = 0; i < allIds.length; i++) {
                allCateIds.add(Long.valueOf(allIds[i]));
            }
        }


        //获取已选中
        ZsCategoryPersonConfig categoryPersonConfig1 = new ZsCategoryPersonConfig();
        categoryPersonConfig1.setItemId(categoryPersonConfig.getItemId());
        if ("5".equals(categoryPersonConfig.getStatus())) {
            categoryPersonConfig1.setStatus("5");
            categoryPersonConfig1.setId(categoryPersonConfig.getId());
        }
        List<ZsCategoryPersonConfig> zsCategoryPersonConfigs = categoryPersonConfigService.selectZsCategoryPersonConfigList(categoryPersonConfig1);
        List<Long> cateIds = new ArrayList<>();
        if (0 < zsCategoryPersonConfigs.size()) {
            for (ZsCategoryPersonConfig zsCategoryPersonConfig : zsCategoryPersonConfigs) {
                String categoryId = zsCategoryPersonConfig.getCategoryId();
                if (null != categoryId && !"".equals(categoryId)) {
                    String[] cids = categoryId.split(",");
                    for (int ci = 0; ci < cids.length; ci++) {
                        cateIds.add(Long.valueOf(cids[ci]));
                    }
                }

            }
        }
        //取出未选中
        List<Long> noIds = new ArrayList<Long>();
        for (Long c : allCateIds) {
            if (!cateIds.contains(c)) {
                noIds.add(c);
            }
        }
        if (null == noIds || 1 > noIds.size()) {
            return new ArrayList<>();
        }

        //获取剩余类目所有上级
        ZsCategory category = new ZsCategory();
        category.setIds(noIds);

        List<ZsCategory> zsCategories = categoryService.selectZsCategoryList(category);
        List<Long> categoryIds = new ArrayList<>();
        for (ZsCategory c : zsCategories) {
            String[] Ancestors = c.getAncestors().split(",");
            for (int ci = 0; ci < Ancestors.length; ci++) {
                categoryIds.add(Long.valueOf(Ancestors[ci]));
            }
        }
        category.setIds(categoryIds);
        List<ZsCategory> categoryList = categoryService.selectZsCategoryList(category);


        return categoryList;
    }

    @Override
    public AjaxResult getSeqByPid(Long pid) {
        ZsCategory category = new ZsCategory();
        category.setPid(pid);
        List<ZsCategory> categoryList = categoryService.selectZsCategoryList(category);
        category.setSeq(1);
        if (null != categoryList && 0 < categoryList.size()) {
            List<ZsCategory> categories = categoryList.stream().sorted(Comparator.comparing(ZsCategory::getSeq).reversed()).collect(Collectors.toList());
            category.setSeq(1 + categories.get(0).getSeq());
        }
        return AjaxResult.success(category);
    }

}
